/**
 * JAVACC DEMO 1.0
 */
package com.apache.portal.tags;

import com.apache.api.vo.ResultEntity;
import com.apache.database.model.Page;
import com.apache.portal.common.enums.FusMethodEnum;
import com.apache.portal.common.oscache.BaseOsCache;
import com.apache.portal.common.oscache.OsCacheOtherManager;
import com.apache.portal.common.util.PortalPubFactory;
import com.apache.rpc.common.LoadRpcService;
import com.apache.tools.ConfigUtil;
import com.apache.tools.RequestTools;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.ToolsUtil;
import net.sf.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * description:  钱包标签定义
 *
 * @author xhe 创建时间：2016-12-05
 */
@SuppressWarnings("serial")
public class FusPortalTag extends TagSupport {

    private String doCode;

    private String pageSize;

    private String objectId;

    private String sqlQuery;//查询条件

    private String attrName;

    public int doStartTag() throws JspException {
        try {
            HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest();
            LoginUser loginUser = (LoginUser) request.getSession().getAttribute("loginUser");
            if (loginUser == null) {
                System.out.println("用户未登录..." + loginUser);
                return super.EVAL_BODY_INCLUDE;
            }

            ResultEntity entity = null;
            Map<String, Object> params = this.getMethodParams(request);
            json2map1(params);
            params = toMapDelNull(params);
            String userEname = loginUser.getUser().getUserEname();//客户编号（资金编号）
            if (StrUtil.isNull(userEname)) {
                System.out.println("资金编号为空，不访问资金钱包模块");
                return super.EVAL_BODY_INCLUDE;
            }
            //封装参数
            params.put("userEname", userEname);
            BaseOsCache oscache = OsCacheOtherManager.getInstance()
                    .getBaseOsCache("fus_my_data_", 60);
            switch (FusMethodEnum.getName(doCode)) {
            case F001://我的小金库账户信息
                //获取结果
                entity = (ResultEntity) LoadRpcService.service()
                        .doServiceClient("fundsService", "fundsMyAccount", params,
                                PortalPubFactory.getInstance().getRpcInfo("funds"));
                //判断结果
                if (entity != null && "true".equals(entity.getResult()) && !"false"
                        .equals(String.valueOf(entity.getEntity()))) {
                    // entity.getEntity(); json类型
                    request.setAttribute("openFunds", "T");//标记已经开通钱包功能
                    request.setAttribute(StrUtil.doNull(attrName, "fusAccout"), entity.getEntity());
                } else {
                    System.out.println(JSONObject.fromObject(entity));
                    String msg = "正在检测您的钱包状态";
                    if ("true".equals(entity.getResult())) {
                        request.setAttribute("openFunds", "F");
                        if (entity != null) {
                            msg = "您还未开通资金账户";
                        }
                    } else {
                        request.setAttribute("openFunds", null);
                    }
                    request.setAttribute("msg", msg);
                }
                break;
            case F004://我的余额
                //获取结果
                entity = (ResultEntity) LoadRpcService.service()
                        .doServiceClient("fundsService", "fundsMyCache", params,
                                PortalPubFactory.getInstance().getRpcInfo("funds"));

                //判断结果
                if (entity != null && "true".equals(entity.getResult())
                        && entity.getEntity() != null && !"false"
                        .equals(String.valueOf(entity.getEntity()))) {
                    // entity.getEntity(); 是 Map<String, Object>类型
                    request.setAttribute(StrUtil.doNull(attrName, "fus"), entity.getEntity());
                }
                break;
            case F006://我的流水明细
                //封装参数
                params.put("pageSize", StrUtil.doNull(pageSize, "10"));
                params.put("pageIndex",
                        StrUtil.doNull(String.valueOf(params.get("pageIndex")), "1"));
                params.put("userid", userEname);
                String actype = String.valueOf(params.get("actype"));
                if (StrUtil.isNotNull(actype)) {
                    params.put("actype", getSqlInStr(actype));
                }
                String cacheKey = oscache.getCacheKey(doCode, params);
                entity = (ResultEntity) oscache.get(cacheKey);
                if (ToolsUtil.isEmpty(entity)) {
                    //获取结果
                    entity = (ResultEntity) LoadRpcService.service()
                            .doServiceClient("fundsService", "fundsFlowing", params,
                                    PortalPubFactory.getInstance().getRpcInfo("funds"));
                    if (!ToolsUtil.isEmpty(entity.getEntity())) {
                        oscache.put(cacheKey, entity);
                    }
                }
                if (entity != null && "true".equals(entity.getResult())
                        && entity.getEntity() != null) {
                    gotoPageInfo(entity.getEntity(), request);
                } else {
                    System.out.println("未获取到对象：" + entity);
                }
                break;
            case fusDeault:
                break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return super.SKIP_BODY;
        }
        return super.EVAL_BODY_INCLUDE;
    }

    private String getSqlInStr(String str) {
        String[] strArr = str.split(",");
        String sqlStr = "";
        for (String a : strArr) {
            sqlStr += "'" + a + "',";
        }
        return sqlStr.substring(0, sqlStr.length() - 1);
    }

    /**
     * json转map
     */
    private void json2map1(Map<String, Object> params) {
        if (StrUtil.isNotNull(sqlQuery)) {
            JSONObject jsonObject = JSONObject.fromObject(sqlQuery);
            Map<String, Object> map1 = JSONObject.fromObject(jsonObject);
            params.putAll(map1);
        }
    }

    private void gotoPageInfo(Object entity, HttpServletRequest request) {
        if (null != entity) {
            Page page = (Page) entity;
            request.setAttribute(StrUtil.doNull(attrName, "fusPages"), page.getPageObjects());
            request.setAttribute("pageSize", page.getPageSize());
            request.setAttribute("pageIndex", page.getPageNeeded());
            request.setAttribute("total", page.getCount());
        }
    }

    public String getDoCode() {
        return doCode;
    }

    public void setDoCode(String doCode) {
        this.doCode = doCode;
    }

    public String getPageSize() {
        return pageSize;
    }

    public void setPageSize(String pageSize) {
        this.pageSize = pageSize;
    }

    @SuppressWarnings("rawtypes")
    private Map<String, Object> getMethodParams(HttpServletRequest request) {
        Map<String, Object> bodyMap = new HashMap<String, Object>();
        bodyMap.put("Client-IP", RequestTools.getIp(request));
        Set keSet = request.getParameterMap().entrySet();
        for (Iterator itr = keSet.iterator(); itr.hasNext(); ) {
            Map.Entry me = (Map.Entry) itr.next();
            Object ok = me.getKey();
            Object ov = me.getValue();
            String[] value = new String[1];
            if (ov instanceof String[]) {
                value = (String[]) ov;
            } else {
                value[0] = ov.toString();
            }
            if (value.length > 0) {
                bodyMap.put(ok.toString(), value[0]);
                request.setAttribute(ok.toString(), value[0]);
            }
        }
        String sysPass = ConfigUtil.getInstance().interfacePass();
        bodyMap.put("sysPass", sysPass);
        return bodyMap;
    }

    public Map<String, Object> toMapDelNull(Map<String, Object> map) {
        Map<String, Object> result = new HashMap<String, Object>();
        for (String key : map.keySet()) {
            if ("class".equals(key))
                continue;
            if (!StrUtil.isNull(String.valueOf(map.get(key))))
                result.put(key, map.get(key));
        }
        return result;
    }

    public String getObjectId() {
        return objectId;
    }

    public void setObjectId(String objectId) {
        this.objectId = objectId;
    }

    public String getSqlQuery() {
        return sqlQuery;
    }

    public void setSqlQuery(String sqlQuery) {
        this.sqlQuery = sqlQuery;
    }

    public String getAttrName() {
        return attrName;
    }

    public void setAttrName(String attrName) {
        this.attrName = attrName;
    }

}
